package com.zhike.service.system.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.liuxp.minioplus.api.StorageService;
import org.liuxp.minioplus.api.model.vo.FileMetadataInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSON;
import com.eva.epc.common.util.CommonUtils;
import com.zhike.common.component.SnowflakeID;
import com.zhike.common.conf.IMBaseConf;
import com.zhike.common.constant.Constants;
import com.zhike.common.constant.SysConfigConstants;
import com.zhike.common.dto.LoginDTO;
import com.zhike.common.dto.R;
import com.zhike.common.dto.UserRegisterDTO;
import com.zhike.common.enums.DeviceEnum;
import com.zhike.common.enums.LoginRegTypeEnum;
import com.zhike.common.enums.ResultCode;
import com.zhike.common.exception.ZkimException;
import com.zhike.common.model.Device;
import com.zhike.common.repository.FileUploadLog;
import com.zhike.common.repository.OperateLog;
import com.zhike.common.utils.CodeUtil;
import com.zhike.common.utils.FileHelper;
import com.zhike.common.utils.IpHelper;
import com.zhike.common.utils.IpdbUtil;
import com.zhike.common.utils.PicUtil;
import com.zhike.common.utils.RedisFactory;
import com.zhike.common.utils.RedisService;
import com.zhike.common.utils.SmsUtil;
import com.zhike.common.vo.LoginResponse;
import com.zhike.common.vo.RosterVO;
import com.zhike.common.vo.UserIdVO;
import com.zhike.common.vo.UserInfo4Cache;
import com.zhike.mapper.system.DeviceMapper;
import com.zhike.mapper.user.UsersMapper;
import com.zhike.service.im.concurrent.CommonConcurrentExecutor;
import com.zhike.service.store.Alioss;
import com.zhike.service.system.ISystemConfigService;
import com.zhike.service.system.ISystemService;
import com.zhike.service.user.IRandomUserNicknameService;
import com.zhike.utils.AccountNumberUtils;
import com.zhike.utils.cache.DeviceInfoCacheProvider;
import com.zhike.utils.cache.UsersInfoCacheProvider;
import com.zhike.utils.file.CustomMultipartFile;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

@Service
@Slf4j
public class SystemServiceImpl implements ISystemService {

    @Resource
    private UsersMapper usersMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private IMBaseConf baseConf;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UsersInfoCacheProvider usersInfoCacheProvider;

    @Autowired
    private DeviceInfoCacheProvider deviceInfoCacheProvider;

    @Resource
    private ISystemConfigService systemConfigService;

    @Autowired
    private IRandomUserNicknameService randomUserNicknameService;

    @Autowired
    private StorageService storageService;

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private Alioss alioss;

    @Autowired
    private SnowflakeID snowflakeID;

    @Value("${jwt.secret: default_value}")
    private String jwtSecret;

    @Value("${jwt.expire: 0}")
    private long jwtExpire;

    @Override
    public R<LoginResponse> login(LoginDTO dto, String ip) {
        // 此校验不会产生同端互斥，而且是登录失败
        // if (StpUtil.isLogin()) {
        // if (StpUtil.getLoginDevice().equals(dto.getDeviceType())) {
        // return R.fail(ResultCode.SYS_RELOGIN_FAIL);
        // }
        // }

        // 校验设备是否支持
        DeviceEnum[] deviceList = DeviceEnum.values();
        if (Arrays.stream(deviceList).noneMatch(device -> device.getValue().equals(dto.getDeviceType()))) {
            return R.rsp(ResultCode.SYS_DEVICE_NOT_SUPPORT);
        }

        UserIdVO userVo = null;
        LoginResponse loginResponse = new LoginResponse();

        if (LoginRegTypeEnum.POHONEANDPASSWORD.getValue().equals(dto.getLoginType())) {// 手机号&密码登录
            userVo = usersMapper.selectUserForLogin(dto.getLoginAccount(),
                    CommonUtils.encyptPassword(dto.getLoginPassword(), ""));
            if (userVo == null) {
                return R.rsp(ResultCode.USER_ACCOUNT_PWD);
            }
        } else if (LoginRegTypeEnum.PHONEANDCODE.getValue().equals(dto.getLoginType())) { // 验证码登录
            if (!checkPhoneCode(dto.getLoginAccount(), dto.getLoginPassword())) {
                return R.rsp(ResultCode.USER_PHONECODE_INVALID);
            }
            userVo = usersMapper.selectUserForLogin(dto.getLoginAccount(), "");
            if (userVo == null) {
                // 自动注册
                UserRegisterDTO urDTO = new UserRegisterDTO();
                urDTO.setPhone(dto.getLoginAccount());
                urDTO.setRegisterDevice(dto.getDeviceType());
                userVo = this.autoRegister(urDTO, ip);
            }
        }

        // 查询设备是否已绑定过
        Device device = deviceMapper.getOneDeviceByUser(userVo.getFakeUid(), dto.getDeviceType());
        if (device == null) {
            // 绑定新设备
            device = new Device();
            device.setFakeUid(userVo.getFakeUid());
            device.setDeviceNo(IdUtil.objectId().toUpperCase());
            device.setDeviceType(dto.getDeviceType());
            device.setStatus(0);
            deviceMapper.saveDevice(device);
            deviceInfoCacheProvider.reloadOneCache(device.getDeviceNo());
        }
        // 返回登录设备唯一码
        loginResponse.setDeviceCode(device.getDeviceNo());
        loginResponse.setFakeId(userVo.getFakeUid());

        // 会话登录 首先在配置文件中，将 isConcurrent 配置为false 指定`账号id`和`设备类型`进行登录
        StpUtil.login(userVo.getFakeUid(), new SaLoginModel()
                .setIsLastingCookie(true)// 是否为持久Cookie（临时Cookie在浏览器关闭时会自动删除，持久Cookie在重新打开后依然存在）
                .setDevice(device.getDeviceType()));
        loginResponse.setToken(StpUtil.getTokenValue());
        log.debug("会话信息: {}", StpUtil.getTokenInfo());

        this.updateUserLoginInfo(ip, userVo.getFakeUid());

        // 设置IM TOKEN
        String deviceNo = device.getDeviceNo();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("device_code", deviceNo);
        map.put("expire_time", jwtExpire);

        String imToken = JWTUtil.createToken(map, jwtSecret.getBytes());
        if (StringUtils.isBlank(imToken)) {
            return R.rsp(ResultCode.IM_CREATE_TOKEN);
        }
        loginResponse.setImToken(imToken);
        usersInfoCacheProvider.reloadOneCache(userVo.getFakeUid());
        deviceInfoCacheProvider.reloadOneCache(deviceNo);
        cacheUserSessionToRedis();
        printUserInfoForLogin(userVo.getFakeUid());

        // 操作日志
        this.syncSaveOprateLog(new OperateLog()
                .setPhone(dto.getLoginAccount())
                .setIp(ip)
                .setOprLevel("info")
                .setOprBz("用户登录")
                .setOprTime(new Date())
                .setOsType(device.getDeviceType())
                .setIpRegion(IpdbUtil.getIpAddress(ip)));
        return R.success(loginResponse);
    }

    public UserIdVO autoRegister(UserRegisterDTO dto, String ip) {
        // 检测随机生成账号是否存在
        String accountNumber = "";
        Integer accountNumberCount = 0;
        do {
            accountNumber = AccountNumberUtils.createAccountNumber();
            accountNumberCount = usersMapper.checkAccountNumber(accountNumber);
        } while (accountNumberCount != 0);
        dto.setAccountNumber(accountNumber);

        // 设置昵称
        dto.setNickname(randomUserNicknameService.getRandomNickName());

        // 生成用户ID
        dto.setFakeUid(IdUtil.simpleUUID());

        dto.setUserSex(1);// 默认男性

        // 头像
        try {
            PicUtil pu = new PicUtil();
            File file = pu.Create(getUserAvatarPath() + dto.getPhone(),
                    pu.Paint(dto.getNickname(), 100, 100, baseConf.getDIR_USER_FONT_DIR(), 45));
            String storage = systemConfigService.getValueByKey("storage", "default");
            if (storage.equals("minio")) {
                FileMetadataInfoVo vo = storageService.createFile(file.getName(),
                        false, dto.getFakeUid(), new FileInputStream(file));
                if (vo != null) {
                    dto.setUserAvatarFileName(vo.getFileKey());
                    log.debug("生成头像成功,fileKey: {}", vo.getFileKey());
                }
            } else if (storage.equals("aliyun")) {
                CustomMultipartFile customMultipartFile = new CustomMultipartFile(file, dto.getPhone());
                String avatarUrl = alioss.upload(customMultipartFile, Constants.UPLOAD_AVATAR, snowflakeID.nextIdStr());
                if (StringUtils.isNotBlank(avatarUrl)) {
                    dto.setUserAvatarFileName(FileHelper.extractPath(avatarUrl));
                    log.debug("生成头像成功 {}", avatarUrl);
                }
            }

        } catch (Exception e) {
            log.warn("手机号:{} 生成头像失败 err:{}, 将生成默认头像", dto.getPhone(), e.getMessage());
        }

        // 保存用户信息
        int res = usersMapper.insertUser(dto, ip, "");
        // 新增用户成功之后
        if (res > 0) {
            log.debug("新用户: {}", dto.getFakeUid());
            // 设置设备标识
            Device device = new Device();
            device.setFakeUid(dto.getFakeUid());
            device.setDeviceNo(IdUtil.objectId().toUpperCase());
            device.setDeviceType(dto.getRegisterDevice());
            device.setStatus(0);
            deviceMapper.saveDevice(device);
            UserIdVO vo = new UserIdVO();
            vo.setFakeUid(dto.getFakeUid());
            return vo;
        }
        return null;
    }

    @Override
    public R<Boolean> userRegister(UserRegisterDTO dto, String ip) {
        // 校验设备是否支持
        DeviceEnum[] deviceList = DeviceEnum.values();
        if (Arrays.stream(deviceList).noneMatch(device -> device.getValue().equals(dto.getRegisterDevice()))) {
            return R.rsp(ResultCode.SYS_DEVICE_NOT_SUPPORT);
        }

        // 手机号是否注册
        Integer phoneCount = usersMapper.checkPhone(dto.getPhone());
        if (phoneCount > 0) {
            return R.rsp(ResultCode.USER_PHONE_REGISTED);
        }

        // 检测随机生成账号是否存在
        String accountNumber = "";
        Integer accountNumberCount = 0;
        do {
            accountNumber = AccountNumberUtils.createAccountNumber();
            accountNumberCount = usersMapper.checkAccountNumber(accountNumber);
        } while (accountNumberCount != 0);
        dto.setAccountNumber(accountNumber);

        // 设置昵称
        dto.setNickname(randomUserNicknameService.getRandomNickName());

        // 头像
        try {
            PicUtil pu = new PicUtil();
            File file = pu.Create(getUserAvatarPath() + dto.getPhone(),
                    pu.Paint(dto.getNickname(), 100, 100, baseConf.getDIR_USER_FONT_DIR(), 45));
            FileMetadataInfoVo vo = storageService.createFile(file.getName(),
                    false, dto.getFakeUid(), new FileInputStream(file));
            if (vo != null) {
                dto.setUserAvatarFileName(vo.getFileKey());
            }
        } catch (Exception e) {
            log.error("手机号:{} 生成头像失败 err:{} 将生成默认头像", dto.getPhone(), e.getMessage());

        }

        if (LoginRegTypeEnum.POHONEANDPASSWORD.getValue().equals(dto.getRegType())) {
            // 设置密码
            String encyptPassword = CommonUtils.encyptPassword(dto.getUserPwd(), "");
            dto.setUserPwd(encyptPassword);
        } else if (LoginRegTypeEnum.PHONEANDCODE.getValue().equals(dto.getRegType())) {
            String sms = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_TYPE_SMS,
                    SysConfigConstants.DEFAULT_KEY);
            if (StringUtils.isNotBlank(sms)) {
                // 判断验证码
                if (!checkPhoneCode(dto.getPhone(), dto.getCheckCode())) {
                    return R.rsp(ResultCode.USER_PHONECODE_INVALID);
                }
            }
        }

        // 生成用户ID
        dto.setFakeUid(IdUtil.simpleUUID());
        // 保存用户信息
        int res = usersMapper.insertUser(dto, ip, "");
        // 新增用户成功之后
        if (res > 0) {
            log.debug("新用户: {}", dto.getFakeUid());

            // 设置设备标识
            Device device = new Device();
            device.setFakeUid(dto.getFakeUid());
            device.setDeviceNo(IdUtil.objectId().toUpperCase());
            device.setDeviceType(dto.getRegisterDevice());
            deviceMapper.saveDevice(device);

            return R.success(true);
        }
        return R.rsp(ResultCode.FAIL);
    }

    /**
     * 用户头像存储路径
     * 
     * @return
     */
    private String getUserAvatarPath() {
        return baseConf.getDIR_USER_AVATAR_UPLOAD() + "/images/";
    }

    /**
     * 缓存用户会话信息到Redis
     */
    private boolean cacheUserSessionToRedis() {
        String fakeUid = (String) StpUtil.getLoginId();
        Device device = deviceMapper.getOneDeviceByUser(fakeUid, StpUtil.getLoginDevice());

        try {
            UserInfo4Cache uc = usersInfoCacheProvider.get(fakeUid);
            if (uc != null && device != null) {
                uc.setCurrentDeviceId(device.getDeviceNo());
                uc.setCurrentDeviceType(device.getDeviceType());
                redisService.set(Constants.USER_INFO_CACHE_KEY_PREFIX + fakeUid,JSON.toJSONString(uc));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 

        return false;
    }

    /**
     * 打印登录用户详情
     */
    private void printUserInfoForLogin(String userId) {
        log.debug("[打印用户信息]========== START ==========");
        UserInfo4Cache uc = usersInfoCacheProvider.get(userId);
        if (uc != null && uc.getDeviceList().size() > 0) {
            log.debug("-手机号: {} -昵称: {}", uc.getPhone(), uc.getNickName());
            for (Device device : uc.getDeviceList()) {
                log.debug(">>>设备号: {}", device.getDeviceNo());
            }

            for (RosterVO f : uc.getRosterList()) {
                log.debug(">>>好友: -昵称: {} -ID: {}", f.getNickname(), f.getFriendUserUid());
            }

        }
        log.debug("[打印用户信息]========== END ==========");
    }

    @Override
    public Boolean logout(HttpServletRequest request) {
        UserInfo4Cache uc = getUserInfo();
        // 当前会话注销登录
        StpUtil.logout();
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        Boolean isLogin = tokenInfo.isLogin;
        if (!isLogin) {
            // 如果没有登录了表示注销成功
            this.syncSaveOprateLog(new OperateLog()
                    .setIp(IpHelper.getIpAddr(request))
                    .setPhone(uc.getPhone())
                    .setOprBz("用户注销")
                    .setOprLevel("info")
                    .setOprTime(new Date())
                    .setOsType(uc.getCurrentDeviceType())
                    .setIpRegion(IpdbUtil.getIpAddress(IpHelper.getIpAddr(request))));
            return true;
        }
        return false;
    }

    @Override
    public UserInfo4Cache getUserInfo() {
        String uId = (String) StpUtil.getLoginId();
        UserInfo4Cache uc = getUserInfo(uId);
        uc.setCurrentDeviceType(StpUtil.getLoginDevice());
        uc.setCurrentDeviceId(this.currentDeviceId(uc.getDeviceList(), uc.getFakeUid(), StpUtil.getLoginDevice()));
        return uc;
    }

    public UserInfo4Cache getUserInfo(String uId) {
        UserInfo4Cache cache = new UserInfo4Cache();

        try {
            String cacheStr = redisService.get(Constants.USER_INFO_CACHE_KEY_PREFIX + uId);
            if (StringUtils.isNotBlank(cacheStr)) {
                cache = JSON.parseObject(cacheStr, UserInfo4Cache.class);
            }
            if (cache == null) {
                log.debug("缓存中不存在,需要从数据库查询数据 uid: {}", uId);
                cache = usersInfoCacheProvider.get(uId);
                redisService.set(Constants.USER_INFO_CACHE_KEY_PREFIX + uId, JSON.toJSONString(cache));
            }

        } catch (Exception e) {
            log.error("获取用户 {} 信息异常 {}", uId, e.getMessage());
        }
        return cache;
    }

    private String currentDeviceId(List<Device> list, String uid, String deviceType) {
        for (Device d : list) {
            if (d.getFakeUid().equals(uid) && d.getDeviceType().equals(deviceType)) {
                return d.getDeviceNo();
            }
        }
        return "";
    }

    @Override
    public Boolean checkPhoneCode(String phone, String codeParam) {
        String smsType = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_TYPE_SMS, "default");
        if (StringUtils.isBlank(smsType)) {
            return true;
        }
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(codeParam)) {
            throw new ZkimException("手机号或验证码是空");
        }
        Jedis jedis = null;

        try {
            jedis = RedisFactory.getJedis();
            // 查询 redis 中的 code
            String code = jedis.get(Constants.REDIS_PHONE_CODE + phone);
            if (code == null) {
                throw new ZkimException("验证码失效，请重新获取！");
            }

            if (code.equals(codeParam)) {
                // 校验正确，需要删除验证码，防止重复使用
                jedis.del(Constants.REDIS_PHONE_CODE + phone);
                jedis.del(Constants.REDIS_PHONE_CODE_TIME + phone);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }

        return false;
    }

    @Override
    public R<String> getPhoneCode(String phone, String modelKey) {
        if (StringUtils.isBlank(phone)) {
            throw new ZkimException(ResultCode.USER_PHONE_EMPTY);
        }

        Jedis jedis = null;
        try {
            jedis = RedisFactory.getJedis();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (jedis.get(Constants.REDIS_PHONE_CODE_TIME + phone) != null) {
            throw new ZkimException(ResultCode.SYS_OPT_BUSY);
        }

        // 默认验证码
        String code = "000000";
        String smsType = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_TYPE_SMS, "default");

        if (StringUtils.isNotEmpty(smsType)) { // 启用
            code = CodeUtil.generateCode6();
            log.info("短信厂商: {} 手机号：{} 生成验证码为：{}", smsType, phone, code);

            // 放入缓存
            jedis.setex(Constants.REDIS_PHONE_CODE + phone, 10 * 60L, code);
            // 设置下一次可请求时间
            jedis.setex(Constants.REDIS_PHONE_CODE_TIME + phone, 1 * 60L, "");

            // 模板内容
            Map<String, String> templateParam = new HashMap<>();
            templateParam.put("code", code);

            // 获取短信平台配置
            String smsJson = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_TYPE_SMS, smsType);
            if (StringUtils.isEmpty(smsJson)) {
                throw new ZkimException(ResultCode.SYS_CONFIG_NOTFOUND);
            }

            try {
                String res = "";
                JSONObject obj = JSONUtil.parseObj(smsJson);
                String accessKeyId = obj.getStr("appKey");
                String accessKeySecret = obj.getStr("secretKey");
                String signName = obj.getStr("sign");
                // 获取模板配置
                String modelJson = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_TYPE_SMS, "model");
                if (StringUtils.isEmpty(modelJson)) {
                    throw new ZkimException(ResultCode.SYS_CONFIG_NOTFOUND);
                }
                JSONArray modelArr = JSONUtil.parseArray(modelJson);
                for (int i = 0; i < modelArr.size(); i++) {
                    if (modelArr.get(i) instanceof JSONObject) {
                        JSONObject m = modelArr.getJSONObject(i);
                        String key = m.getStr("key");
                        if (key.equals(modelKey)) {
                            String smsModel = m.getStr("modelId");
                            res = smsUtil.send(smsUtil.buildClient(accessKeyId, accessKeySecret),
                                    smsUtil.buildRequest(phone, signName, smsModel, JSONUtil.toJsonStr(templateParam)));
                            return R.success(res);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                log.error("{}", e.getMessage());
                return R.rsp(ResultCode.OTHER_ERROR);
            } finally {
                jedis.close();
            }
        }
        return R.success(code);
    }

    @Override
    public void updateUserLoginInfo(String ip, String uid) {
        CommonConcurrentExecutor.getInstance().execute(new Runnable() {

            @Override
            public void run() {
                if (usersMapper.updateUserLoginInfo(ip, uid) > 0) {
                    log.debug("更新用户 {} 登录信息 ip: {}", uid, ip);
                }
            }

        });

    }

    @Override
    public void syncSaveOprateLog(OperateLog oprLog) {
        CommonConcurrentExecutor.getInstance().execute(new Runnable() {

            @Override
            public void run() {
                OperateLog res = mongoTemplate.save(oprLog);
                if (res != null) {
                    log.debug("插入一条用户操作日志: {}", JSONUtil.toJsonStr(oprLog));
                }
            }

        });
    }

    public void syncSaveFileUploadLog(FileUploadLog oprLog) {
        CommonConcurrentExecutor.getInstance().execute(new Runnable() {

            @Override
            public void run() {
                FileUploadLog res = mongoTemplate.save(oprLog);
                if (res != null) {
                    log.debug("插入一条文件上传日志: {}", JSONUtil.toJsonStr(oprLog));
                }
            }

        });
    }

}
